/*
 * easysmtp - A simple C lib in Linux to help you send mails in an easy way
 * Copyright (C) 2012-2013, easysmtp developers and contributors
 *
 * easysmtp is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * easysmtp is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with easysmtp; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "change64.h"

//暂存字符串ASCII码的二进制
int binary[10005] = {0};  
//base64转码表
char base64[65] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop"
			"qrstuvwxyz0123456789+/"};  
//base64加密后字符串
char change[10005] = {0};   
int flag = 0;
int flag_change = 0;

//ascii值转换成二进制表示
void 
atob(int change_num)
{
	int temp[8] = {0}, i = 7;
	while(change_num) {
		temp[i--] = change_num % 2;
		change_num /= 2;
	}
	for(i = 0; i < 8; i++) {
		binary[flag++] = temp[i];
	}
	return;
}

//二进制表示六位取一次变为ascii表示的字母
void 
btoa(int len)
{
	int i, j, temp;
	for(i = 0; i < flag; i+=6) {
		temp = 0;
		for(j = i; j < i+6; j++) {
			temp = temp*2 + binary[j];
		}
		change[flag_change++] = base64[temp];	
	}
	//补=号
	if(len == 0) {
		return;
	}
	else if(len == 1) {
		strcat(change, "==");
	}
	else {
		strcat(change, "=");
	}
	return;
}

//转换成base64的函数
void 
to64(int *str, int len)
{
	flag = 0;
	flag_change = 0;
	memset(change, 0, sizeof(change));
	memset(binary, 0, sizeof(binary));
	int i;
	//是否为三的倍数，否则要补一个=或者两个=
	for(i = 0; i < len; i++) {
		atob(str[i]);
	}
	if(len%3 != 0) {	
		if(len%3  == 1) {
			flag += 4;
		}
		else {
			flag += 2;
		}
	}
	btoa(len%3);
}

void 
cto64(char *str, int len) 
{
	int ntemp[len], i; 

	for(i = 0; i < len; i++) {
		ntemp[i] = str[i];	
	}
	to64(ntemp, len);
}

void 
ucto64(unsigned char *str, int len) 
{
	int ntemp[len], i;

	for(i = 0; i < len; i++) {
		ntemp[i] = str[i];
	}
	to64(ntemp, len);
}
